package com.vue.power.backend.sys.util;

import com.vue.power.backend.sys.dto.RoleTreeDto;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 类描述：实现组装菜单树的数据
 */
public class TreeInstall {

    /**
     * 功能描述：实现递归组装选中的菜单节点的数据
     * @param treeList
     * @param treeMap
     * @return
     */
    public static List<RoleTreeDto> installCheckTree(List<RoleTreeDto> treeList, Map<String,Object> treeMap){
        List<RoleTreeDto> trees = new ArrayList<>();
        for(RoleTreeDto roleTree : treeList ){
            if(roleTree.getParentTreeId().equals("0")){
                roleTree.setChildren(getCheckChild(roleTree.getTreeId(),treeList,treeMap));
                // 用于防止子节点部分选中，而父节点全部选中
                if(roleTree.getChildren().size()>0){
                    for(RoleTreeDto checkTree:roleTree.getChildren()){
                        if(!checkTree.isChecked()){
                            roleTree.setChecked(false);
                            break;
                        }
                    }
                }
                trees.add(roleTree);
            }
        }
        return trees;
    }

    // 递归遍历菜单节点
    private static List<RoleTreeDto> getCheckChild(String id, List<RoleTreeDto> trees, Map<String,Object> treeMap) {
        List<RoleTreeDto> childList = new ArrayList<>();
        for (RoleTreeDto tree : trees) {
            if(tree.getParentTreeId().equals(id)){
                tree.setChildren(getCheckChild(tree.getTreeId(),trees,treeMap));
                if(treeMap.get(tree.getTreeId())!=null){
                    tree.setChecked(true);
                }else{
                    tree.setChecked(false);
                }
                if(tree.getChildren().size()>0){
                    for(RoleTreeDto checkTree:tree.getChildren()){
                        if(!checkTree.isChecked()){
                            tree.setChecked(false);
                            break;
                        }
                    }
                }
                childList.add(tree);
            }
        }
        return childList;
    }

    /**
     * 功能描述：实现树形菜单数据的组装
     * @param treeList
     */
    public static  List<RoleTreeDto> installTree(List<RoleTreeDto> treeList){
        List<RoleTreeDto> trees = new ArrayList<>();
        for(RoleTreeDto roleTree : treeList ){
            if(roleTree.getParentTreeId().equals("0")){
                roleTree.setChildren(getChild(roleTree.getTreeId(),treeList));
                trees.add(roleTree);
            }
        }
        return trees;
    }

    // 递归遍历菜单节点
    private static List<RoleTreeDto> getChild(String id, List<RoleTreeDto> trees) {
        List<RoleTreeDto> childList = new ArrayList<>();
        for (RoleTreeDto tree : trees) {
            if(tree.getParentTreeId().equals(id)){
                tree.setChildren(getChild(tree.getTreeId(),trees));
                childList.add(tree);
            }
        }
        return childList;
    }

}
